
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;

import entity.MasterConfig;
import entity.ServerDockerContainterProcess;
import service.DSTServerDockerService;
import utils.Base;
import utils.DockerManager;

import javax.servlet.Servlet;

import java.util.LinkedList;
import java.util.List;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {

    public static int init(DockerManager dockerManager)
    {
        List<String> ids = dockerManager.getAllContainterId();
        for (String id : ids) {
            // dockerManager.stopContainer(id);
            dockerManager.deleteContainer(id);
        }
        return 0;
    }

    public static void main(String[] args) throws Exception {
        // 创建 Jetty 服务器，监听端口8080
        Server server = new Server(8080);

        // 设置 Servlet 上下文处理
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        MasterConfig masterConfig = new MasterConfig();
        if (masterConfig.load(new File("config.properties")) != 0)
        {
            System.err.println("load config err.");
            return ;
        } else {
            System.out.println(masterConfig.toString());
        }

        File uploadDirFile = new File(masterConfig.getUploadDir());
        if (!uploadDirFile.exists())
        {
            uploadDirFile.mkdir();
        }

        DockerManager dockerManager = new DockerManager();
        DSTServerDockerService dockerService = new DSTServerDockerService(dockerManager, masterConfig);
        LinkedList<ServerDockerContainterProcess> serverProcessesList = new LinkedList<>();

        if (init(dockerManager) != 0)
        {
            return ;
        }

        String img = masterConfig.getDst_docker_image();
        Path dstPath = Paths.get(masterConfig.getDstPath());
        Path dstBinPath = dstPath.resolve("bin");
        Path dstExePath = dstBinPath.resolve("dontstarve_dedicated_server_nullrenderer");
        Path archivePath = Paths.get(masterConfig.getArchivePath()).toAbsolutePath();

        for(Path archiveItemPath: Base.getAllSubPathName(archivePath)) {
            String fileName = archiveItemPath.getFileName().toString();
            if(Base.isValidArchive(fileName))
            {
                for(Path subpath: Base.getAllSubPathName(archiveItemPath)) {
                    String subfileName = subpath.getFileName().toString();

                    ServerDockerContainterProcess serverDockerContainterProcess = 
                        dockerService.createNewServerContainerWithLimit(
                            img, fileName, subfileName,
                            1024, 2*1024, 0.85f
                        );

                    serverProcessesList.add(serverDockerContainterProcess);
                }
            }
        }

        System.out.println("============================== init finish ============================");

        // 注册 MultiRouteServlet
        context.addServlet(new ServletHolder(
            (Servlet) new MultiRouteServlet(
                serverProcessesList, 
                dockerService,
                masterConfig)
        ), "/*");

        // 启动服务器
        server.start();
        System.out.println("Java Server started at http://localhost:8080/");

        server.join();
    }
}